<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>编辑角色</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/layuimini/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/layuimini/css/public.css" media="all">
    <link rel="stylesheet" href="/static/admin/dtree/dtree.css">
    <link rel="stylesheet" href="/static/admin/dtree/font/dtreefont.css">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>
<form class="layui-form layuimini-form">
    <input type="hidden" name="id"/>
    <div class="layui-form-item">
        <label class="layui-form-label required">角色名称</label>
        <div class="layui-input-block">
            <input type="text" name="roleName" lay-verify="required|roleName" lay-reqtext="角色名称不能为空"
                   placeholder="请输入角色名称"
                   value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">描述</label>
        <div class="layui-input-block">
            <textarea name="description" class="layui-textarea"
                      placeholder="请输入角色描述" lay-verify="description"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">级别</label>
        <div class="layui-input-block">
            <input type="number" name="sort" placeholder="请输入角色级别" value="" class="layui-input" lay-verify="number|sort"
                   required="">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">颜色</label>
        <div class="layui-input-block">
            <div>
                <div id="color-select" lay-verify="colorVer"></div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">状态</label>
        <div class="layui-input-block">
            <input type="checkbox" name="status" lay-skin="switch" lay-text="启用|停用" value="1" checked/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">权限</label>
        <div class="layui-input-block">
            <div id="treeDiv" style="overflow: auto;" lay-verify="menuTree">
                <ul id="menuTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="saveBtn">确认修改</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script src="/static/admin/layuimini/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="/static/admin/layuimini/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/static/admin/xm-select/xm-select.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
<script th:inline="javascript" type="text/javascript">
    layui.use(['form', 'dtree'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.jquery,
            dtree = layui.dtree;

        //渲染多选下拉框
        var colorSelect = xmSelect.render({
            el: '#color-select',
            language: 'zn',
            radio: true,
            clickClose: true,
            model: {
                label: {
                    type: 'text',
                    text: {
                        template: function (item, sels) {
                            return '<span>' + item.name + '</span>';
                        },
                    },
                }
            },
            template({name, value}) {
                let color = 'layui-bg-' + value;
                return name + '<span class="' + color + '" style="position: absolute; right: 10px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>'
            },
            data: [
                {name: '赤', value: 'red'},
                {name: '橙', value: 'orange'},
                {name: '绿', value: 'green'},
                {name: '青', value: 'cyan'},
                {name: '蓝', value: 'blue'},
                {name: '黑', value: 'black'},
                {name: '灰', value: 'gray'},
            ]
        });

        //渲染数据
        let role = [[${role}]];
        $('.layui-form input[name="id"]').val(role.id);
        $('.layui-form input[name="roleName"]').val(role.roleName);
        $('.layui-form textarea[name="description"]').val(role.description);
        $('.layui-form input[name="sort"]').val(role.sort);
        $('.layui-form input[name="status"]').prop('checked', (role.status === 1));
        colorSelect.setValue([role.color]);
        form.render();

        //获取菜单树
        let data = null;
        $.ajax({
            url: '/admin/menu/checkbox-tree',
            type: 'GET',
            async: false,
            success: function (result) {
                data = result.data;
            }
        });

        let DTree = dtree.render({
            elem: "#menuTree",
            initLevel: 2,
            load: true,
            line: true,
            checkbar: true,
            data: data,
            done: function (res, $ul, first) {
                if (first) {
                    let menuIdList = role.menuIdList;
                    console.log(menuIdList)
                    menuIdList.push(0);
                    console.log(3)
                    dtree.chooseDataInit("menuTree", menuIdList); // 数组形式
                }
            }
        });


        //自定义验证规则
        form.verify({
            //验证用户名
            roleName: function (value) { //value：表单的值、item：表单的DOM对象
                if (value.length < 2 || value.length > 16) {
                    return '角色名称长度为2-16个字符'
                }
                if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                    return '角色名称不能有特殊字符';
                }
                if (/^\d+\d+\d$/.test(value)) {
                    return '角色名称不能全为数字';
                }
            },
            //验证描述
            description: function (value) {
                if (value.length > 100) {
                    return '描述长度在100个字符以内'
                }
            },
            //验证颜色
            colorVer: function () {
                if (colorSelect.getValue('value').length <= 0) {
                    return '请选择颜色';
                }
            },
            //验证级别
            sort: function (value) { //value：表单的值、item：表单的DOM对象
                if (value < 1 || value > 1024) {
                    return '级别数值在1-1024之间'
                }
            },
            //验证权限
            menuTree: function () {
                let checkData = dtree.getCheckbarNodesParam("menuTree");
                if (checkData.length <= 0) {
                    return '请选择权限'
                }
            }
        });

        //获取选中ID列表
        function getCheckIdList(checkData) {
            if (checkData == null || checkData.length <= 0) {
                return [];
            }
            let result = [];
            for (let i = 0; i < checkData.length; i++) {
                if (checkData[i].nodeId !== "0") {
                    result.push(Number(checkData[i].nodeId));
                }
            }
            return result;
        }

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            //获取颜色
            data.field.color = colorSelect.getValue('value')[0];
            //获得选中的菜单ID列表
            let checkData = dtree.getCheckbarNodesParam("menuTree");
            data.field.menuIdList = getCheckIdList(checkData);
            axios({
                method: 'put',
                url: '/admin/role',
                data: data.field,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
            }).then((response) => {
                Swal.fire({
                    icon: 'success',
                    title: '保存成功',
                    showConfirmButton: false,
                    timer: 1500,
                    onClose: () => {
                        var parentLayer = parent.layer;
                        var iframeIndex = parentLayer.getFrameIndex(window.name);
                        parent.location.reload();
                        parentLayer.close(iframeIndex);
                    }
                });
            }).catch((error) => {
                Swal.fire({
                    icon: 'error',
                    title: '保存失败！',
                    text: `${error.response.data.message}`,
                });
            })
            return false;
        });
    });

</script>
</body>
</html>
